<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addRolesDialogVisible = true">
            添加角色
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 树状展开区域 -->
        <el-table-column type="expand" width="50px">
          <template #default="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : 'bdbottom', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightsById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightsById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre>{{ scope.row }}</pre>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="400px">
          <template #default="scope">
            <!-- 编辑按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑按钮"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showRolesDialog(scope.row.id)"
                >编辑</el-button
              >
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除按钮"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeRolesById(scope.row.id)"
                >删除</el-button
              >
            </el-tooltip>
            <!-- 分配权限 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightsDialog(scope.row)"
                >分配权限</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 隐藏的添加权限区域 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addRolesDialogVisible"
        width="50%"
        @close="addRolesDialogClose"
      >
        <!-- 内容区域 -->
        <el-form
          ref="addRolesFormRef"
          :model="rolesForm"
          :rules="rolesFormRules"
          label-width="90px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles"> 确 定</el-button>
        </span>
      </el-dialog>
      <!-- 隐藏的编辑权限区域 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editRolesDialogVisible"
        width="50%"
        @close="editRolesDialogClose"
      >
        <!-- 内容区域 -->
        <el-form
          ref="editRolesFormRef"
          :model="rolesForm"
          :rules="rolesFormRules"
          label-width="90px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesForm.roleName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRolesInfo"> 确 定</el-button>
        </span>
        <!-- 分配权限的对话框 -->
      </el-dialog>
    </el-card>
    <!-- 分配权限区域 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <span
        ><el-tree
          :data="rightsList"
          :props="treeProps"
          show-checkbox
          default-expand-all
          :default-checked-keys="defKeys"
          node-key="id"
          ref="treeRef"
        ></el-tree>
      </span>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 当前分配权限的角色id
      roleId: "",
      //所有角色的权限列表
      rolesList: [],
      //获取角色表单
      rolesForm: {},
      // 获取权限列表
      rightsList: {},
      // 默认勾选中的节点id值数组
      defKeys: [],
      // 树形控件属性绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 是否打开添加角色区域
      addRolesDialogVisible: false,
      // 是否打开权限编辑区域
      editRolesDialogVisible: false,
      //控制分配权限区域
      setRightDialogVisible: false,
      // 权限规则
      rolesFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 10, trigger: "blur" },
        ],
        roleDesc: [],
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.$message.success("获取成功");
      this.rolesList = res.data;
    },
    //监听添加用户对话框的关闭事件
    addRolesDialogClose() {
      // resetField重置表单项
      // 选择form的dom元素来重置
      this.$refs.addRolesFormRef.resetFields();
    },
    // 点击按钮 添加新用户
    addRoles() {
      this.$refs.addRolesFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写正确信息");
        const { data: res } = await this.$http.post("roles", this.rolesForm);
        if (res.meta.status !== 201) return this.$message.error("添加角色失败");
        this.$message.success("添加角色成功");
        this.addRolesDialogVisible = false;
        this.getRolesList();
      });
    },
    async removeRolesById(id) {
      // 该方法点击确定结果为confirm 取消则为cancel 利用if判断结果来执行不同操作
      const confirmResult = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult === "confirm") {
        const { data: res } = await this.$http.delete("roles/" + id);
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败");
        }
        this.$message.success("删除成功");
        this.getRolesList();
      } else {
        return this.$message.info("取消删除");
      }
    },

    // 控制修改用户权限区域是否打开
    async showRolesDialog(id) {
      this.editRolesDialogVisible = true;
      // console.log(id);
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.$message.success("获取成功");
      this.rolesForm = res.data;
      this.rolesForm.id = id;
    },
    // 关闭修改权限区域
    editRolesDialogClose() {
      // resetField重置表单项
      // 选择form的dom元素来重置
      this.$refs.editRolesFormRef.resetFields();
    },
    //修改用户权限并提交
    editRolesInfo() {
      this.$refs.editRolesFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发送网络请求
        const { data: res } = await this.$http.put(
          "roles/" + this.rolesForm.id,
          {
            roleName: this.rolesForm.roleName,
            roleDesc: this.rolesForm.roleDesc,
          }
        );
        if (res.meta.status !== 200) return this.$message.error("编辑失败");
        this.editRolesDialogVisible = false;
        this.getRolesList();
        this.$message.success("编辑成功");
      });
    },
    // 根据id删除权限
    async removeRightsById(roles, rightsId) {
      // 该方法点击确定结果为confirm 取消则为cancel 利用if判断结果来执行不同操作
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult === "confirm") {
        const { data: res } = await this.$http.delete(
          `roles/${roles.id}/rights/${rightsId}`
        );
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败");
        }
        this.$message.success("删除成功");
        //把服务器返回的值重新赋值给角色的子属性
        roles.children = res.data;
      } else {
        return this.$message.info("取消删除");
      }
    },
    // 展示分配权限的对话框
    async showSetRightsDialog(role) {
      this.roleId = role.id;
      //获取所有权限类型
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.$message.success("获取成功");
      this.rightsList = res.data;
      // console.log(this.rightsList);
      // 获取三级节点的id
      this.getLeafKeys(role, this.defKeys);
      this.setRightDialogVisible = true;
    },
    // 通过递归获取三级权限的id
    getLeafKeys(node, arr) {
      if (!node.children) return arr.push(node.id);
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 点击分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      // console.log(keys);
      const idStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) return this.$message.error("分配权限失败");
      this.$message.success("分配权限成功");
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
